﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Diagnostics;
using You2V.Data.Shared;
using You2V.LocalDBLayer;
using Microsoft.Win32;
using System.Data;

namespace You2VTool
{
    /// <summary>
    /// Interaction logic for Student2012.xaml
    /// </summary>
    public partial class Student2012Main : Window
    {
        private List<StudentInfo2012> Student2012List;

        public Student2012Main()
        {
            InitializeComponent();
            RefreshStudentList();
        }

        private void dg_Student2012_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            StudentInfo2012 SelectedStudent = (StudentInfo2012)this.dg_Student2012.SelectedItem;

            if (SelectedStudent != null)
            {
                // 之前list应该只select有限数据，此处应该读取明细数据
                //StudentInfo2012 StudentForEdit = StudentDBL.Instance.GetStudent2012ByStudentNumber(SelectedStudent.StudentNumber);
                StudentDBL StudentDBL = new StudentDBL();
                StudentInfo2012 StudentForEdit = StudentDBL.GetStudent2012ByID(SelectedStudent.ID);

                student2012InputControl.LoadStudent(StudentForEdit, true);
                this.OKButton.IsEnabled = true;
                this.CancelButton.IsEnabled = true;
                
                //如果还没有发布，则允许发布或者删除
                if (StudentForEdit != null && StudentForEdit.UploadStatus == -1)
                {
                    this.PublishButton.IsEnabled = true;
                    this.DeleteButton.IsEnabled = true;
                }
                else
                {
                    this.PublishButton.IsEnabled = false;
                    this.DeleteButton.IsEnabled = false;
                }
            }
        }

        private bool SaveCurrentStudent()
        {
            if (!student2012InputControl.GetDataFromUI())
                return false;

            if (student2012InputControl.IsEditing)
            {
                // save to DB
                StudentDBL StudentDBL = new StudentDBL();
                if (!StudentDBL.UpdateStudent2012(student2012InputControl.CurrentStudent))
                {
                    MessageBox.Show("保存失败, 错误编号57483", "数据库错误");
                    return false;
                }
            }
            else
            {
                // 保存新学生信息
                StudentDBL StudentDBL = new StudentDBL();
                if (!StudentDBL.SaveNewStudent2012(student2012InputControl.CurrentStudent))
                {
                    MessageBox.Show("保存失败，错误编号 6258", "数据库错误");
                    return false;
                }
            }

            return true;
        }

        private void OKButton_Click(object sender, RoutedEventArgs e)
        {
            if (!SaveCurrentStudent())
                return;

            //刷新DataGrid
            RefreshStudentList();
        }

        private void RefreshStudentList()
        {
            dg_Student2012.ItemsSource = null;
            StudentDBL StudentDBL = new StudentDBL();
            Student2012List = StudentDBL.GetStudent2012List(string.Empty);

            dg_Student2012.ItemsSource = Student2012List;

            student2012InputControl.Empty();

            this.NewButton.IsEnabled = true;
            this.NewFromExcelButton.IsEnabled = true;
            this.OKButton.IsEnabled = false;
            this.CancelButton.IsEnabled = false;
            this.PublishButton.IsEnabled = false;
            this.DeleteButton.IsEnabled = false;
        }

        private void NewButton_Click(object sender, RoutedEventArgs e)
        {
            //todo, 之前有未保存的需要保存一下
            student2012InputControl.NewStudent();
            this.NewButton.IsEnabled = false;
            this.NewFromExcelButton.IsEnabled = false;
            this.OKButton.IsEnabled = true;
            this.CancelButton.IsEnabled = true;
            this.PublishButton.IsEnabled = true;
            this.DeleteButton.IsEnabled = false;    //新学生，没必要删除，不保存即可
        }

        private void CancelButton_Click(object sender, RoutedEventArgs e)
        {
            if (student2012InputControl.IsDataDirty())
            {
                if (MessageBox.Show("数据已修改，您确认要放弃目前的修改吗?", "确认放弃", MessageBoxButton.YesNo) != MessageBoxResult.Yes)
                    return;
            }

            //刷新DataGrid
            RefreshStudentList();
        }

        private void TriggerSearch()
        {
            string keyWord = this.SearchText.Text;

            if (string.IsNullOrWhiteSpace(keyWord))
            {
                RefreshStudentList();
                return;
            }

            StudentDBL StudentDBL = new StudentDBL();
            Student2012List = StudentDBL.GetStudent2012List(keyWord);

            dg_Student2012.ItemsSource = Student2012List;

            this.NewButton.IsEnabled = true;
            this.NewFromExcelButton.IsEnabled = true;
            this.OKButton.IsEnabled = false;
            this.CancelButton.IsEnabled = false;
        }

        private void SearchText_KeyDown(object sender, KeyEventArgs e)
        {
            // 因为性能差，敲回车才执行
            if (e.Key == Key.Enter)
            {
                TriggerSearch();
            }
        }

        private void SearchButton_Click(object sender, RoutedEventArgs e)
        {
            TriggerSearch();
        }

        private void CancelSearchButton_Click(object sender, RoutedEventArgs e)
        {
            this.SearchText.Text = string.Empty;
            RefreshStudentList();
        }

        private void PublishButton_Click(object sender, RoutedEventArgs e)
        {
            //检查是否处于可以上传的状态
            if (student2012InputControl.CurrentStudent == null || student2012InputControl.CurrentStudent.ID == null)
            {
                MessageBox.Show("没有选中任何学生", "操作错误");
                return;
            }

            //先保存
            if (!SaveCurrentStudent())
                return;

            if (student2012InputControl.CurrentStudent.UploadStatus != -1)
            {
                MessageBox.Show("该学生已经上传到后台系统，请勿重复上传", "错误操作");
                return;
            }

            if (MessageBox.Show("发布到后台以后，您将无法删除该学生信息了，是否继续?", "确认发布", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                //模拟发布
                string sqlCommand = "Update Student2012 SET UploadStatus = 0 WHERE ID={" + student2012InputControl.CurrentStudent.ID + "}";

                if (DBAccess.RunCommand(sqlCommand))
                {
                    MessageBox.Show("谢谢试用！该功能未完全实现，不过该学生状态已经模拟变成已发布", "模拟完成");
                }
                else
                {
                    MessageBox.Show("发布失败, 错误号 192848");
                }

                RefreshStudentList();
            }
        }

        private void DeleteButton_Click(object sender, RoutedEventArgs e)
        {
            //确认可以删除的条件
            if (student2012InputControl.CurrentStudent == null || student2012InputControl.CurrentStudent.ID == null)
            {
                MessageBox.Show("没有选中任何学生", "操作错误");
                return;
            }


            //该操作不需要先保存！

            if (student2012InputControl.CurrentStudent.UploadStatus != -1)
            {
                MessageBox.Show("该学生已经上传到后台系统，无法进行删除操作，特殊情况请联系助学组长从后台删除", "错误操作");
                return;
            }

            if (MessageBox.Show("您确定要删除该学生信息吗？", "确认删除", MessageBoxButton.YesNo) == MessageBoxResult.Yes)
            {
                //删除(TODO 暂时只考虑单机版本情况, 对于网络版本不能简单删除，而是要记录删除操作以便网络同步)
                string sqlCommand = "DELETE FROM Student2012 WHERE ID={" + student2012InputControl.CurrentStudent.ID + "}";

                if (DBAccess.RunCommand(sqlCommand))
                {
                    RefreshStudentList();
                    MessageBox.Show("删除成功", "删除成功");    //也许可以不显示
                }
                else
                {
                    MessageBox.Show("删除失败, 错误号 23849");
                    return; //不刷新界面
                }
            }
        }

        private void NewFromExcelButton_Click(object sender, RoutedEventArgs e)
        {
            //todo, 之前有未保存的需要保存一下

            OpenFileDialog open = new OpenFileDialog();
            open.Title = "选择新学生Excel数据";
            open.Filter = "Excel文件（*.xls)|*.xls|所有文件|*.*";
            if ((bool)open.ShowDialog().GetValueOrDefault())
            {
                string Filename = open.FileName;

                string ErrorMessage = string.Empty;
                StudentInfo2012 student = ExcelAccess.GetStudentFromExcel(Filename, ref ErrorMessage);

                if (student != null)
                {
                    student2012InputControl.NewStudentFromExcel(student);
                    this.NewButton.IsEnabled = false;
                    this.NewFromExcelButton.IsEnabled = false;
                    this.OKButton.IsEnabled = true;
                    this.CancelButton.IsEnabled = true;
                    this.PublishButton.IsEnabled = true;
                    this.DeleteButton.IsEnabled = false;    //新学生，没必要删除，不保存即可
                }
                else
                {
                    MessageBox.Show("导入学生Excel失败，错误信息:\r\n" + ErrorMessage, "数据格式错误");
                }
            }
        }
    }
}
